package com.linkgie.galaxyframework.security.ca;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import com.linkgie.galaxyframework.utils.ApplicationException;
import com.linkgie.galaxyframework.utils.RuntimeStatus;
import com.linkgie.galaxyframework.utils.service.ServiceContext;
import com.linkgie.galaxyframework.utils.service.ServiceProvider;

/**
 * 证书基础设施；
 */
public class CertificateInfrastructure {

    private static Map<String, CertificateService> servicesMap;

    private static synchronized void init() {
        if (servicesMap != null) {
            return;
        }

        // 装载当前的类加载器下所有的证书服务提供者；
        ServiceContext<CertificateService> providerManager = ServiceContext.load(CertificateService.class);
        if (providerManager.getSize() == 0) {
            providerManager.loadFrom(CertificateInfrastructure.class.getClassLoader());
        }

        // 注册密码服务；
        Collection<ServiceProvider<CertificateService>> providers = providerManager.getProviders();

        Map<String, CertificateService> services = new LinkedHashMap<>();
        for (ServiceProvider<CertificateService> provider : providers) {
            CertificateService srv = provider.getService();
            services.put(srv.getAlgorithm(), srv);
        }

        CertificateInfrastructure.servicesMap = services;
    }

    /**
     * 支持的算法列表；
     * 
     * @return
     */
    public static Set<String> getAlgorithms() {
        if (servicesMap == null) {
            init();
        }
        return servicesMap.keySet();
    }

    public static CertificateService getCertificateService(String algorithm) {
        if (servicesMap == null) {
            init();
        }
        CertificateService certificateService = servicesMap.get(algorithm);
        if (certificateService == null) {
            throw new CertificateException("No certificate service provider of algorithm \""+algorithm+"\"!");
        }
        return certificateService;
    }

}
